package DataConnectionInterface;

import Helper.GameException;

public class ConnectionPool {
	
	public static int numberOfConnections;
	private static ConnectionPool connectionPool = null;
	private GameDataConnectionInterface[] pool = new GameDataConnection[numberOfConnections];
	private boolean[] isConnectionAvailable = new boolean[numberOfConnections];
	
	/**
	 * 
	 * @return the single instance of ConnectionPool
	 * @throws GameException
	 */
	public static synchronized ConnectionPool getInstance() throws GameException {
		if (connectionPool == null)
			connectionPool = new ConnectionPool();
		return connectionPool;
	}
	
	/**
	 * Private constructor, creates all connections
	 * @throws GameException
	 */
	private ConnectionPool() throws GameException {
		for (int i = 0; i < numberOfConnections; i++) {
			pool[i] = new GameDataConnection();
			isConnectionAvailable[i] = true;
		}
	}
	
	/**
	 * 
	 * @return an available connection to the database
	 */
	public synchronized GameDataConnectionInterface getConnection() {
		while (true) {
			for (int i = 0; i < numberOfConnections; i++) {
				if (isConnectionAvailable[i]) {
					isConnectionAvailable[i] = false;
					return pool[i];
				}
			}
		}
	}
	
	/**
	 * Returns a connection to the pool of free connections
	 * @param connection - the connection to return to the pool
	 */
	public synchronized void returnConnection(GameDataConnectionInterface connection) {
		for (int i = 0; i < numberOfConnections; i++) {
			if (connection == pool[i]) // comparing by == makes sense here
				isConnectionAvailable[i] = true;
		}
	}
}
